package com.link.linkupjavaweb.controller.user;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.dto.RankDTO;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.service.RankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 排行榜Controller
 */
@Controller
@RequestMapping("/user/rank")
public class RankController {
    
    @Autowired
    private RankService rankService;
    
    /**
     * 排行榜页面
     */
    @GetMapping
    public String rankPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        if (user == null) {
            return "redirect:/user/login";
        }
        
        model.addAttribute("user", user);
        return "user/rank/index";
    }
    
    /**
     * 获取排行榜数据
     */
    @GetMapping("/list")
    @ResponseBody
    public Result<Map<String, Object>> getRankList(
            @RequestParam(required = false, defaultValue = "100") Integer limit,
            HttpSession session) {
        try {
            User user = (User) session.getAttribute(Constants.SESSION_USER);
            if (user == null) {
                return Result.error("请先登录");
            }
            
            // 获取排行榜列表
            List<RankDTO> rankList = rankService.getRankList(limit);
            
            // 获取当前用户排名
            Integer myRank = rankService.getUserRank(user.getId());
            
            Map<String, Object> data = new HashMap<>();
            data.put("rankList", rankList);
            data.put("myRank", myRank);
            data.put("total", rankList.size());
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取排行榜失败：" + e.getMessage());
        }
    }
}

